<template>
	<el-button class="m-b20" @click="addHandel()"> 添加 </el-button>

	<el-tree
		:data="state.dataSource"
		class="m-b20"
		node-key="id"
		default-expand-all
		:expand-on-click-node="false"
	>
		<template #default="{ node, data }">
			<div class="custom-tree-node d-flex">
				<div class="name">{{ data.stageName }}</div>
				<div class="time m-l20">
					{{ data.predictStartTime }} 至 {{ data.predictEndTime }}
				</div>
				<div class="department m-l20">{{data.responsibleDepartmentName ||  data.stageDepartmentName }}</div>
				<div class="userName m-l20">{{data.responsibleUserName || data.stageUserName}}</div>
				<span>
					<span
						class="projectPeople"
						style="margin-left: 8px"
						@click="update(node, data)"
					>
						编辑
					</span>
					<span class="projectPeople" @click="append(node, data)">
						添加下级
					</span>
					<span
						class="projectPeople"
						style="margin-left: 8px"
						@click="remove(node, data)"
					>
						删除
					</span>
				</span>
			</div>
		</template>
	</el-tree>

	<!-- 添加编辑弹窗	-->
	<public-dialog
		:title="title"
		:width="'45%'"
		v-model:visible="visible"
		@onConfirm="onConfirm"
	>
		<div class="public-dialog-content d-flex j-center a-center">
			<el-form
				:model="dialogForm"
				ref="dialogFormRef"
				class="demo-form-inline"
				label-width="140px"
			>
				<el-form-item label="阶段名称" prop="">
					<el-input v-model="dialogForm.stageName" placeholder="请输入阶段名称" />
				</el-form-item>
				<el-form-item label="部门名称" prop="">
					<el-select
						style="width: 100% !important;"
						v-model="dialogForm.responsibleDepartmentId"
						clearable
						filterable
						@change="changeHandel(dialogForm.responsibleDepartmentId)"
						placeholder="请选择"
					>
						<el-option
							v-for="item in departmentList"
							:key="item.departmentId"
							:label="item.departmentName"
							:value="item.departmentId"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="责任人名称" prop="">
					<el-select
							style="width: 100% !important;"
						v-model="dialogForm.responsibleUserId"
						clearable
						filterable
						placeholder="请选择"
					>
						<el-option
							v-for="item in state.departmentPersonList"
							:key="item.userId"
							:label="item.userName"
							:value="item.userId"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="阶段实施时间" prop="">
					<el-date-picker
						v-model="dialogForm.time"
						@change="handelChangeTime"
						type="datetimerange"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						format="YYYY-MM-DD"
						size="large"
						value-format="YYYY-MM-DD"
						:disabledDate="disabledDateFn"
					/>
				</el-form-item>
			</el-form>
		</div>
	</public-dialog>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import PublicDialog from "@/components/PublicDialog.vue";
import {ElButton, ElDatePicker, ElForm, ElFormItem, ElMessage, ElSelect, ElTree,} from "element-plus";
import {department, projectPhase,} from "@/api/project";
import {snowflakeGenerator} from 'snowflake-id-js';
import {getURLhandler} from "@/views/constructionProjectManage/static/utools";
import {useRoute} from "vue-router";

const props = defineProps({
	projectTypeId: {
		type: String,
		default: "",
	},
	projectId: {
		type: String,
		default: "",
	},
	departmentList:{
		type:Array,
		default:[]
	},
	startTime:{
		type:String,
		default:''
	},
	endTime:{
		type:String,
		default:''
	}
});
const title = ref("编辑");

const dialogForm = ref({
	projectStageId: "",
	responsibleUserId: "",
	responsibleDepartmentId: "",
	stageName: "",
	projectId: "",
	parentProjectStageId: "",
	stageOrder: "",
	level: "",
	predictStartTime: "",
	predictEndTime: "",
});

const state = reactive({
	allDepartmentList: [],
	departmentPersonList: [],
	userByDepartmentList: [],
	dataSource: [],
	currentData:null
});

// 新增
const handelChangeTime = (e) => {
	if (e && e.length > 0) {
		dialogForm.value.predictStartTime = e[0];
		dialogForm.value.predictEndTime = e[1];
	}
};

const addHandel = () => {
	const generator = snowflakeGenerator(512);
	title.value = "新增";
	dialogForm.value = {
		projectStageId:generator.next().value,
		type:10,
		level: 1,
		stageOrder: state.dataSource.length + 1,
		parentProjectStageId: "",
		projectId: props.projectId,
		stageName: "",
		responsibleDepartmentId: "",
		responsibleUserId: "",
	};
	visible.value = true;
};


const visible = ref(false);
const emits = defineEmits(["setStageTimeChange"]);

//添加下级 tree按钮
const append = (node, data) => {
	if(!data.predictStartTime){
		return ElMessage.warning('请先完善上级阶段时间!');
	}
	state.currentData = data;
	const generator = snowflakeGenerator(512);
	title.value = "添加下级";
	dialogForm.value = {
		projectStageId:generator.next().value,
		type:10,
		level: data.level + 1,
		stageOrder: node.parent.data.children
			? node.parent.data.children.length + 1
			: 1,
		parentProjectStageId: data.projectStageId,
		projectId: props.projectId,
		stageName: "",
		responsibleDepartmentId: "",
		responsibleUserId: "",
		predictStartTime: "",
		predictEndTime: "",
	};
	visible.value = true;
	if(data.predictStartTime && data.predictEndTime){
		emits("getStageTimeChange", {
			predictStartTime: data.predictStartTime,
			predictEndTime: data.predictEndTime,
		});
	}
};

/**
 * 删除节点
 * @param treeList
 * @param id
 */
const removeNodeInTree=(treeList, id)=> { // 通过id从数组（树结构）中移除元素
	if (!treeList || !treeList.length) {
		return
	}
	for (let i = 0; i < treeList.length; i++) {
		if (treeList[i].projectStageId === id) {
			treeList.splice(i, 1);
			break;
		}
		removeNodeInTree(treeList[i].children, id)
	}
}

//删除 tree按钮
const remove = (node, data) => {
	if(data.children && Array.isArray(data.children) && data.children.length!==0){
		return ElMessage.warning('请逐级删除节点!');
	}

	stageRemove({
		projectId: props.projectId,
		projectStageId: data.projectStageId,
	},()=>{
		removeNodeInTree(state.dataSource,data.projectStageId);
	});
};

//编辑 tree按钮
const update = (node, data) => {
	state.currentData = data;
	title.value = "编辑";
	dialogForm.value = {
		...data,
	};

	dialogForm.value.time = [
		dialogForm.value.predictStartTime,
		dialogForm.value.predictEndTime,
	];

	getLeaderByDepartmentId(data.responsibleDepartmentId);
	setTimeout(() => {
		visible.value = true;
	},300);
};

// 弹出层 提交
const onConfirm = () => {
	if (title.value === "添加下级") {
		stageCreate('添加下级');
	} else if (title.value === "编辑") {
		stageUpdate();
	} else if (title.value === "新增") {
		stageCreate('新增');
	}
};

/**
 * 新增项目实施单个阶段(新增/新增子级)
 * @param type
 */
const stageCreate = (type) => {
	dialogForm.value['responsibleDepartmentName'] = props.departmentList.filter(item=>{
		if(item.departmentId+'' === dialogForm.value.responsibleDepartmentId+''){
			return item
		}
	})[0].departmentName

	dialogForm.value['responsibleUserName'] = state.departmentPersonList.filter(item=>{
		if(item.userId === dialogForm.value.responsibleUserId){
			return item
		}
	})[0].userName

	if(type==='新增'){
		state.dataSource.push(dialogForm.value);
	}else if(type==='添加下级'){
		state.currentData.children===undefined?state.currentData.children=[dialogForm.value]:state.currentData.children.push(dialogForm.value);
	}

	ElMessage.success("操作成功");
	visible.value = false;
};


/**
 * 修改项目实施单个阶段
 */
const stageUpdate = () => {
	if(dialogForm.value.responsibleDepartmentId){
		dialogForm.value['stageDepartmentName'] = props.departmentList.filter(item=>{
			if(item.departmentId+'' === dialogForm.value.responsibleDepartmentId+''){
				return item
			}
		})[0].departmentName
	}

	if(dialogForm.value.responsibleUserId){
		dialogForm.value['stageUserName'] = state.departmentPersonList.filter(item=>{
			if(item.userId === dialogForm.value.responsibleUserId){
				return item
			}
		})[0].userName
	}

	console.log('dialogForm.value',dialogForm.value)

	setData(state.currentData,dialogForm.value);
	const generator = snowflakeGenerator(512);
	state.currentData.projectStageId = generator.next().value;
	if(state.currentData && Array.isArray(state.currentData.children) && state.currentData.children.length!==0){
		for(let item of state.currentData.children){
			item.parentProjectStageId = state.currentData.projectStageId;
		}
	}
	visible.value = false;
};


/* 删除项目实施单个阶段 接口*/
const stageRemove = (param,callback) => {
	projectPhase.stageRemove(param).then((res) => {
		if (res.code === '200') {
			if(callback)callback(res);
		}
	});
};

/**
 *
 * @param tree
 * @return {*[]}
 */
const treeToArray = (tree) => {
	var res = []
	for (const item of tree) {
		const { children, ...i } = item
		if (children && children.length) {
			res = res.concat(treeToArray(children))
		}
		res.push(i)
	}
	return res
}


/**
 * 批量新增项目阶段
 */
let route = useRoute();
const createStage = (callback) => {
	let data = treeToArray(state.dataSource);
	for(let item of data){
		item.projectId = props.projectId;
		if(item.predictStartTime===null || item.predictStartTime===''){
			return ElMessage.warning('请完善阶段时间!')
		}
	}

	let params = {
		stages:data
	};
	projectPhase.createStage(params).then(res=>{
		if(res.code === '200'){
			if(callback)callback(res);
		}
	});
}

// 获取所有部门
/*const getAllDepartments = () => {
	department.getAllDepartments().then((res) => {
		const { code, data, msg } = res;
		if (code === '200') {
			alert(1)
			state.allDepartmentList = data;
		}
	});
};*/

// 获取项目 负责人
const getLeaderByDepartmentId = (responsibleDepartmentId) => {
	department.getUserByDepartmentId(responsibleDepartmentId).then((res) => {
		const { code, data, msg } = res;
		if (code === '200') {
			state.departmentPersonList = data;
		}
	});
};

// 获取项目实施阶段配置
const getProjectPhase = () => {
	projectPhase
		.getProjectPhase2({
			projectId: props.projectId,
			projectTypeId: props.projectTypeId,
		})
		.then((res) => {
			const { code, data, msg } = res;
			if (code === '200') {
				state.dataSource = data.stages;
			}
		});
};

const changeHandel = (e) => {
	if (e) {
		dialogForm.value.responsibleUserId = "";
		getLeaderByDepartmentId(e);
	}
};

/**
 *
 * @param data1
 * @param data2
 */
const setData = (data1,data2) => {
  for (let k1 in data1){
		for (let k2 in data2){
			if(k1===k2){
				data1[k1] = data2[k2];
			}
		}
	}
}

/**
 * 限制日期范围
 * @param time
 */
const disabledDateFn = (time) => {
	console.log('props.startTime',props.startTime)
	if(props.startTime!==''){
		return  !(time.getTime() >= new Date(props.startTime).getTime()-86400000) || !(time.getTime() <= new Date(props.endTime).getTime())
	}
	if(getURLhandler(route.path).startTime){
		return  !(time.getTime() >= new Date(getURLhandler(route.path).startTime).getTime()) || !(time.getTime() <= new Date(getURLhandler(route.path).endTime).getTime())
	}
}

watch(
	() => visible.value,
	(value) => {
		if (!value) {
			dialogForm.value = {};
		}
	}
);

onMounted(() => {
	// getAllDepartments();
	if (props.projectId) {
		getProjectPhase();
	}
});
defineExpose({
	state,
	createStage
});
</script>
<style lang="scss" scoped>
.projectPeople {
	color: #fff;
	cursor: pointer;

	text-align: center;
	font-size: 12px;
	height: 20px;
	line-height: 20px;
	margin-left: 10px;
	background-color: #d4ae85;
	border-radius: 10px;
	padding-left: 5px;
	padding-right: 5px;
}

.custom-tree-node {
	.name {
		min-width: 100px;
		height: 20px;
		background: #f7f7fa;
		border-radius: 6px;
		padding: 0 10px;
		text-align: center;
		font-size: 14px;
		color: #1a1a1a;
		line-height: 20px;
	}
	.time,
	.department,
	.userName {
		min-width: 104px;
		height: 20px;
		line-height: 20px;
		text-align: center;
		padding: 0 10px;
		font-size: 14px;
		color: #1a1a1a;
		border-radius: 6px;
		border: 1px solid #e3e7f1;
	}
}
:deep(.el-tree-node__content, .el-tree-node__children) {
	margin-bottom: 10px !important;
}
</style>
